import axios from '@/js_sdk/gangdiedao-uni-axios'
import env from './env'

/**
 * 请求接口日志记录
 */
function _reqlog(req) {
    if (process.env.NODE_ENV === 'development') {
        // console.log("请求地址：" + req.url, req.data || req.params)
    }
    //TODO 调接口异步写入日志数据库
}


/**
 * 响应接口日志记录
 */
function _reslog(res) {
    if (process.env.NODE_ENV === 'development') {
        console.log(`${res.config.url}响应结果：`, res)
    }
}

// 创建自定义接口服务实例
const http = axios.create({
    baseURL: env.baseURL,
    timeout: 6000,
    // #ifdef H5
    withCredentials: true,
    // #endif
    headers: {
        'Content-Type': 'application/json',
        //'X-Requested-With': 'XMLHttpRequest',
    },
})

let token = '';

// axios.defaults.baseURL = env.baseURL;

uni.getStorage({
    key: 'storage_key',
    success: function (res) {
        console.log(res.data);
		token = res.data;
    }
});

//添加一个请求拦截器
http.interceptors.request.use(function(config) {
	/* let user = JSON.parse(window.sessionStorage.getItem('access-user'));
	if (user) {
		token = user.token;
	} */
	if(!token || token.length === 0){
		console.log("-------add token------");
		uni.getStorage({
		    key: 'storage_key',
		    success: function (res) {
		        console.log(res.data);
				token = res.data;
		    }
		});
	}
	config.headers.common['token'] = token;
	config.headers.openid = token;
	
	_reqlog(config);
	
	return config;
}, function(error) {
	console.info("error: ");
	console.info(error);
	return Promise.reject(error);
});


// 拦截器 在请求之后拦截
http.interceptors.response.use(response => {
    _reslog(response)
    // code...
	return response;
})

export default http
